package com.tianqu.tms.www.transfer.controller;

import java.io.File;
import java.net.URLDecoder;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferAcceptedInfoBo;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.MarketCarService;
import com.tianqu.tms.entity.Sequence;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.TransferFinanceInfo;
import com.tianqu.tms.entity.TransferProcessHistory;

/**
 * 库存车辆受理-更新数据 controller
 * @author mufeiyu
 *
 */
public class CarStockAcceptTransferInfoResultController extends TmsController {
	private Logger logger = Logger.getLogger(CarStockAcceptTransferInfoResultController.class);

	private static final String CHECK_CAR_PRINT = "checkCarPrint";
	private static final String ACCEPT_TYPE = "acceptType";
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			

            String checkCarPrint = uc.getParameter(CHECK_CAR_PRINT);
			String acceptType = uc.getParameter(ACCEPT_TYPE);
			
			String basicCarId = uc.getParameter("basicCarId");
			String licensePlate = uc.getParameter("licensePlateStr");
			licensePlate = URLDecoder.decode(licensePlate,"utf-8");
			String businessType = uc.getParameter("businessType");
			String cardType = uc.getParameter("cardType");
			String vin = uc.getParameter("vinStr");
			TmsUserProfile profile = uc.getUserProfile();
			Sequence seq = Sequence.getInstance();
			String serial = seq.getSerial(6);
			if(serial.indexOf(" ") != -1){
				serial = serial.replace(" ", "");
			}
			TransferAcceptedInfo transferAccept = TransferAcceptedInfo.getInstance();
			MarketCarService carService = MarketCarService.getInstance();
			carService = carService.findCarServiceInfoBySerial(basicCarId);
			Car car = Car.getInstance();
			car = car.findCarBySerial(basicCarId);
			File inFile = null;
			File outFile1 = null;
			if("1".equals(businessType)){
				//过户业务基本信息
				transferAccept.setSerial(serial);//车辆流水号
				transferAccept.setMarketType(1);//车辆库存类型
				transferAccept.setLicensePlate(licensePlate);//车牌号码
				transferAccept.setCy_cardType(cardType);//号牌种类
				transferAccept.setCarClass(2);//车辆分类
				transferAccept.setVin(vin);
				if("0".equals(cardType)){
					transferAccept.setLicensePlateCol("2");//号牌颜色
				}else if("1".equals(cardType)){
					transferAccept.setLicensePlateCol("1");//号牌颜色
				}				
				//缴费金额
				if(carService.getTransferPrice() != 0){
					transferAccept.setTransferPrice(carService.getTransferPrice());
				}
				transferAccept.setStatus(1);//过户状态
				transferAccept.setSourceType(1);//车辆来源状态
				transferAccept.setInsertUserid(profile.getUniqueId());//插入用户
				transferAccept.setUpdateUserId(profile.getUniqueId());//更新用户
				transferAccept.setBasicCarId(car.getSerial());//车辆编号
				transferAccept.setVendorId(car.getVendorId());//车辆品牌ID
				transferAccept.setBrandId(car.getBrandId());//车系ID
				transferAccept.setCarStyleId(car.getCarStyleId());//车辆款式ID
				transferAccept.setCarName(car.getCarName());//车辆名字
				transferAccept.setIsMatch(car.getIsMatch());//车款是否匹配
				transferAccept.setMemberId(String.valueOf(car.getMemberId()));//商户会员ID
				//modify by huangwei 20170501
				if("1".equals(acceptType))transferAccept.setPreTransfer(2);
				else transferAccept.setPreTransfer(1);
				if("2".equals(checkCarPrint)){
					transferAccept.setCy_printNum(1);
					transferAccept.setCy_printUserId(profile.getUniqueId());
				}
				
				if(!StringUtil.isNullOrBlank(car.getPhoto_1())){
					String path = Registry.getConfig(TmsConstants.TMS_WEB_BASE_IMAGE_PATH);
					path = path.replace("/image/", "");
					inFile = new File(path+car.getPhoto_1());
					String outFile = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY)+"/"+serial+"/");
					outFile1 = new File(outFile+serial+"_1"+".jpg");
					boolean result = CopyFile.copy(inFile, outFile1);
					if(result){
						//查验照片
						transferAccept.setPhoto_1(ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY)+"/"+serial+"/")+serial+"_1"+".jpg");
					}
				}
				
			}else if("2".equals(businessType)){
				//过户业务基本信息
				transferAccept.setSerial(serial);//车辆流水号
				transferAccept.setMarketType(1);//车辆库存类型
				transferAccept.setLicensePlate("");//车牌号码
				transferAccept.setCy_cardType(cardType);//号牌种类
				transferAccept.setCarClass(1);//车辆分类
				transferAccept.setVin(vin);
				transferAccept.setLicensePlateCol("0");//号牌颜色
				transferAccept.setStatus(1);//过户状态
				transferAccept.setSourceType(1);//车辆来源状态
				transferAccept.setInsertUserid(profile.getUniqueId());//插入用户
				transferAccept.setUpdateUserId(profile.getUniqueId());//更新用户
				transferAccept.setBasicCarId(car.getSerial());//车辆编号
				transferAccept.setVendorId(car.getVendorId());//车辆品牌ID
				transferAccept.setBrandId(car.getBrandId());//车系ID
				transferAccept.setCarStyleId(car.getCarStyleId());//车辆款式ID
				transferAccept.setCarName(car.getCarName());//车辆名字
				transferAccept.setIsMatch(car.getIsMatch());//车款是否匹配
				transferAccept.setMemberId(String.valueOf(car.getMemberId()));//商户会员ID
				if(!StringUtil.isNullOrBlank(car.getPhoto_1())){
					String path = Registry.getConfig(TmsConstants.TMS_WEB_BASE_IMAGE_PATH);
					path = path.replace("/image/", "");
					inFile = new File(path+car.getPhoto_1());
					String outFile = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY)+"/"+serial+"/");
					outFile1 = new File(outFile+serial+"_1"+".jpg");
					boolean result = CopyFile.copy(inFile, outFile1);
					if(result){
						//查验照片
						transferAccept.setPhoto_1(ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY)+"/"+serial+"/")+serial+"_1"+".jpg");
					}
				}
			}
			//插入 过户业务基本信息表（tms_transfer_accepted_info）
			transferAccept.insertCarTranserAcceptInfo(transferAccept);
			
			//过户流程操作信息
			//插入 过户流程操作记录表（tms_transfer_process_history）
			TransferProcessHistory transferProcess = TransferProcessHistory.getInstance();
			transferProcess.setSerial(serial);
			transferProcess.setBusinessType(1);
			transferProcess.setInsertUserId(profile.getUniqueId());			
			//第一条信息
			transferProcess.insertHisInfoAtAssess(transferProcess);
			
			if(("1".equals(businessType)) && carService.getCheckPrice() == 1){//modify by huangwei 20170501
				transferProcess.setSerial(serial);
				transferProcess.setBusinessType(8);
				transferProcess.setInsertUserId(1);
				//第二条信息
				transferProcess.insertHisInfoAtAssess(transferProcess);
			}
			
			//过户业务的财务收费信息
			TransferFinanceInfo transferFinance = TransferFinanceInfo.getInstance();
			int priceType = 0;
			int checkPriceType = 0;
			transferFinance.setSerial(serial);
			//缴费金额
			if(carService.getCheckPrice() == 1){//modify by huangwei 20170501
				transferFinance.setCheckPrice(carService.getTransferPrice());//modify by huangwei 20170501
				transferFinance.setCheckPriceUserId(1);
				transferFinance.setCheckPriceChargeType(3);
				checkPriceType = 1;
			}else {				
				transferFinance.setCheckPriceChargeType(1);
			}
			
			//交易票收费金额
			if("1".equals(businessType)){//modify by huangwei 20170501
				transferFinance.setTransferPrice(0);//modify by huangwei 20170501
				transferFinance.setTransferPriceUserId(1);
				transferFinance.setTransferPriceChargeType(3);
				priceType = 1;
			}
			//插入 tms_transfer_finance_info（过户业务的财务收费信息表）
			transferFinance.insertFinanceInfo(transferFinance,priceType,checkPriceType);
			
			
			carService.setSerial(basicCarId);
			carService.setCheckStatus(1);
			carService.setCheckImgPath("");
			carService.setCheckUser("");
			carService.setCheckTime(null);
			carService.setCheckValidTime(null);
			carService.setIsValid(3);
			carService.setIsRebate(-1);
			//modify by huangwei 20170501
			if(carService.getCheckPrice() == 1) carService.setCheckPrice(2);
			else carService.setCheckPrice(carService.getCheckPrice());
			carService.setTransferPrice(0);
			
			//更新库存车辆业务表（tms_market_car_service）
			carService.updateCarServiceAllInfo(carService);
			
			
			uc.setAttribute("checkSerial", serial);
			
			controller.commit();
			
			//接口编号：401；【TMS_web】库存车辆受理 - 点击开始受理 =》【TMS_app】同步
			TransferAcceptedInfoBo acceptedInfoBo = new TransferAcceptedInfoBo();
			acceptedInfoBo.setSerial(serial);
			acceptedInfoBo.setMarketType(transferAccept.getMarketType());
			acceptedInfoBo.setLicensePlate(transferAccept.getLicensePlate());
			acceptedInfoBo.setCyCardType(Integer.valueOf(transferAccept.getCy_cardType()));
			acceptedInfoBo.setCarClass(transferAccept.getCarClass());
			acceptedInfoBo.setLicensePlateCol(Integer.valueOf(transferAccept.getLicensePlateCol()));
			acceptedInfoBo.setBasicCarId(transferAccept.getBasicCarId());
			acceptedInfoBo.setVin(transferAccept.getVin());
			acceptedInfoBo.setVendorId(transferAccept.getVendorId());
			acceptedInfoBo.setBrandId(transferAccept.getBrandId());
			acceptedInfoBo.setCarStyleId(transferAccept.getCarStyleId());
			acceptedInfoBo.setCarName(transferAccept.getCarName());
			acceptedInfoBo.setIsMatch(transferAccept.getIsMatch());
			acceptedInfoBo.setPhoto_1(transferAccept.getPhoto_1());
			acceptedInfoBo.setMemberId(transferAccept.getMemberId());
			acceptedInfoBo.setStatus(transferAccept.getStatus());
			acceptedInfoBo.setMarketNo(TmsConstants.MARKET_NO);

			WeChatMqApi.getInstance().call(acceptedInfoBo);
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
}
